package com.future.singleton;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInput;
import java.io.ObjectInputStream;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;
import java.util.HashSet;
import java.util.Set;

/**
 * Description:
 *
 * @author weiruibai.vendor
 * Date: 2021/9/8 10:47
 */
public class Test {

    public static void main(String[] args) throws Exception {
        Set<Integer> set = new HashSet<>();
        set.add(EnumSingleton.getInstance().hashCode());
        System.out.println("test start....");
        for (int i = 0; i < 10000; i++) {
            new Thread(() -> {
                try {
                    Thread.sleep(20);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                if (set.add(EnumSingleton.getInstance().hashCode())) {
                    throw new RuntimeException("不一样的地址");
                }
            }).start();

        }
        System.out.println("test end");
        testSerialize();
    }

    // 序列化测试
    private static void testSerialize() throws Exception {
        EnumSingleton singleton = EnumSingleton.getInstance();
        singleton.setData("test");
        ObjectOutput oo = new ObjectOutputStream(new FileOutputStream("single2"));
        oo.writeObject(singleton);

        File file = new File("single2");
        ObjectInput oi = new ObjectInputStream(new FileInputStream(file));
        EnumSingleton obj = (EnumSingleton) oi.readObject();
        System.out.println(obj.getData());
        if (obj != singleton) {
            throw new RuntimeException("序列化后对象变了");
        }
    }

}
